package com.usian.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.feign.AccountFeign;
import com.usian.feign.StockFeign;
import com.usian.mapper.OrderMapper;
import com.usian.pojo.Order;
import com.usian.service.OrderService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private StockFeign stockFeign;
    @Autowired
    private AccountFeign accountFeign;

    @GlobalTransactional //全局控制分布式事务
    @Override
    public boolean createOrder(Order order) {

        /**
         * 1:校验参数
         * 2：写订单表
         * 3：扣减库存
         * 4：扣减账户余额
         */
        boolean result =false;

        if(order!=null &&order.getUserId()!=null &&order.getSkuId()!=null && order.getSkuNum()!=null
                && order.getPrice()!=null){

            boolean b = this.save(order);
            if(b){
                //下单成功后 减库存
                stockFeign.jian(order.getSkuId(), order.getSkuNum());
                //减余额
                accountFeign.deduction(order.getUserId(),order.getSkuNum()*order.getPrice());

                int a =100/0;

                result =true;
            }
        }
        return result;
    }
}
